#!/bin/bash

# 快速部署Ubuntu编译版本到服务器

set -e

echo "🚀 SPAM3UK Ubuntu版本快速部署"
echo "================================"

# 服务器信息
SERVER="118.145.200.164"
USER="anders"
PASSWORD="nHC83lCH0r1KcaIzF00Y6w=="
DEPLOY_PATH="/data/prod/spam3uk"

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 检查文件
if [[ ! -f "spam3uk-ubuntu" ]]; then
    echo "❌ 未找到Ubuntu可执行文件，请先运行 ./build-ubuntu.sh"
    exit 1
fi

echo "1. 准备部署文件..."
PACKAGE_FILE=$(ls spam3uk-ubuntu-*.tar.gz | head -1)
if [[ -z "$PACKAGE_FILE" ]]; then
    echo "创建部署包..."
    PACKAGE_FILE="spam3uk-ubuntu-deploy.tar.gz"
    tar -czf $PACKAGE_FILE \
        spam3uk-ubuntu \
        spam4uk-config.prod.template.json \
        manage.sh \
        quick-start.sh \
        startup-guide.md
fi

echo -e "${GREEN}✅ 部署包: $PACKAGE_FILE${NC}"

echo -e "\n2. 上传到服务器..."
if command -v sshpass &> /dev/null; then
    # 使用sshpass自动上传
    sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no \
        $PACKAGE_FILE $USER@$SERVER:/tmp/
    
    echo -e "\n3. 在服务器上部署..."
    sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no $USER@$SERVER << 'EOF'
        cd /tmp
        echo "📦 解压部署包..."
        mkdir -p /data/prod/spam3uk-new
        tar -xzf spam3uk-ubuntu-*.tar.gz -C /data/prod/spam3uk-new
        
        echo "🔄 备份现有部署..."
        if [ -d "/data/prod/spam3uk" ]; then
            sudo cp -r /data/prod/spam3uk /data/prod/spam3uk-backup-$(date +%Y%m%d-%H%M%S)
        fi
        
        echo "📂 部署新版本..."
        sudo mkdir -p /data/prod/spam3uk
        sudo cp -r /data/prod/spam3uk-new/* /data/prod/spam3uk/
        sudo chown -R anders:anders /data/prod/spam3uk
        
        cd /data/prod/spam3uk
        chmod +x spam3uk-ubuntu manage.sh quick-start.sh
        
        echo "🔧 配置生产环境..."
        if [ ! -f "spam4uk-config.prod.json" ] && [ -f "spam4uk-config.prod.template.json" ]; then
            cp spam4uk-config.prod.template.json spam4uk-config.prod.json
            echo "⚠️  请编辑 spam4uk-config.prod.json 配置数据库信息"
        fi
        
        echo "✅ 部署完成！"
        echo "当前目录: $(pwd)"
        ls -la spam3uk-ubuntu
        
        echo "🚀 启动服务..."
        if ./manage.sh status 2>/dev/null | grep -q "active"; then
            echo "停止现有服务..."
            sudo systemctl stop spam3uk 2>/dev/null || true
        fi
        
        # 更新systemd服务文件
        sudo tee /etc/systemd/system/spam3uk.service > /dev/null << 'SYSTEMD_EOF'
[Unit]
Description=SPAM3UK Ford Vehicle Scraper Service
After=network.target mysql.service

[Service]
Type=simple
User=anders
WorkingDirectory=/data/prod/spam3uk
ExecStart=/data/prod/spam3uk/spam3uk-ubuntu
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
SYSTEMD_EOF

        sudo systemctl daemon-reload
        sudo systemctl enable spam3uk
        sudo systemctl start spam3uk
        
        echo "⏳ 等待服务启动..."
        sleep 3
        
        if sudo systemctl is-active --quiet spam3uk; then
            echo "✅ 服务启动成功！"
            sudo systemctl status spam3uk --no-pager
            
            echo "🧪 测试API..."
            if curl -s http://localhost:5700/health > /dev/null; then
                echo "✅ API响应正常"
                curl -s http://localhost:5700/health
            else
                echo "⚠️  API响应异常，请检查配置"
            fi
        else
            echo "❌ 服务启动失败"
            sudo journalctl -u spam3uk --no-pager -l
        fi
        
        echo "🎉 Ubuntu版本部署完成！"
        echo "访问地址: http://118.145.200.164:5700"
EOF

else
    echo -e "${YELLOW}提示: 请手动上传和部署${NC}"
    echo "1. 上传部署包:"
    echo "   scp $PACKAGE_FILE $USER@$SERVER:/tmp/"
    echo ""
    echo "2. SSH到服务器:"
    echo "   ssh $USER@$SERVER"
    echo ""
    echo "3. 执行部署:"
    echo "   cd /tmp"
    echo "   tar -xzf $PACKAGE_FILE -C /data/prod/spam3uk"
    echo "   cd /data/prod/spam3uk"
    echo "   chmod +x spam3uk-ubuntu"
    echo "   ./spam3uk-ubuntu"
fi

echo -e "\n${GREEN}✅ 部署脚本执行完成！${NC}"
